# -*- coding: utf-8 -*-
from  sqlalchemy.sql.expression import func, select
from flask import Blueprint,Flask
from flask import render_template, session,request,jsonify,redirect,url_for
import json
import os
import time
import datetime
import base64

from sqlalchemy import Column, String, create_engine,DateTime,Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
    __tablename__ = 'black_list'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name= Column(String(50))
    is_del=Column(Integer, default=0)
    img = Column(String(50))
    introduce = Column(String(100))
    time = Column(DateTime, default=datetime.datetime.now())

engine = create_engine('postgresql://postgres:123456@localhost:5432/test',pool_size = 20, max_overflow=50, pool_timeout=100)
DBSession = sessionmaker(bind=engine)
session = DBSession()

basedir = os.path.abspath(os.path.dirname(__file__))
general_manager_bp=Blueprint('general_manager_bp',__name__, template_folder='templates')
import sys
app=Flask(__name__)
defaultencoding = 'utf-8'

@app.route('/picture_list',methods=['GET'])
#@login_required
def picture_list():

        picture=session.query(User).filter(User.is_del==0).all()
        return render_template('picture_list.html',picture=picture)

@app.route('/picture_add',methods=['GET','POST'])
# @login_required
def picture_add():
    return render_template('picture_add.html')

@app.route('/add_picture',methods=['GET','POST'])

def add_picture():
    t = str(time.time())  # 秒级时间戳
    img= request.files['img']
    new_name =  str(t) + ".jpg"
    img.save(os.path.join('C:/test/PycharmProjects/flask_opencv/static/images/', new_name))

    img_url="http://[2001:da8:a80a:3003:d95f:90a7:2ce3:ae14]:8088/static/images/"+new_name
    post_json = request.form.get('json')
    data = json.loads(post_json)
    groupId = "123"
    userId = data.get('crname')
    imageType = "BASE64"
    with open(os.path.join('C:/test/PycharmProjects/flask_opencv/static/images/', new_name), "rb") as f:
        image = base64.b64encode(f.read())
    image = str(image, 'utf-8')
    client.addUser(image, imageType, groupId, userId)
    new_user = User(name=data.get('crname'), introduce=data.get("crrecommend"),img=img_url)
    session.add(new_user)
    session.commit()
    session.close()
    return "ok"


@app.route('/delete_picture',methods=['POST'])

def delete_picture():
    post_json = request.get_data()
    if post_json == None:
        return 'error'
    data = json.loads(post_json)
    id = data.get('id')
    user = session.query(User).filter(User.id == id).update(
        {
            'is_del': 1
        }
    )
    return 'success'

if __name__ == "__main__":
    app.run(host='::',port=8088,debug=True)